<template>
	<view class="addaddress">
		<view class="maps">
			<map :scale="14" style="width:100%;height:100%;" :markers="markers"></map>
		</view>
		<view class="box">
			<view class="form">
				<view class="item flex">
					<view class="fl">所在地区</view>
					<view class="fr flex bd0">

						<picker @confirm="selectArea" mode="region" v-model="show"
							:area-code='["13", "1303", "130304"]'>

						</picker>

						<input type="text" disabled @tap="show=true" class="intxt" v-model="address"
							placeholder="街道、楼牌号等详细地址" placeholder-style="color:#CBCBCB">
					</view>
				</view>
				<view class="item flex" style="align-items: flex-start;">
					<view class="fl" style="padding:40rpx 0;">地址</view>
					<view class="fr" @tap="chooseLocation">
						<view class="yhname flex">
							<input type="text" class="intxt" disabled placeholder="请选择详细地址"
								placeholder-style="color:#CBCBCB">
							<!-- <arrow-right :size="13" color="#CBCBCB"></arrow-right> -->
						</view>
						<view class="area" v-if="address">{{address}}</view>
					</view>
				</view>
				<view class="item flex">
					<view class="fl">详细地址</view>
					<view class="fr flex bd0">
						<input type="text" class="intxt" v-model="detailed_address" placeholder="街道、楼牌号等详细地址"
							placeholder-style="color:#CBCBCB">
					</view>
				</view>
			</view>
			<view class="form f2">
				<view class="item flex">
					<view class="fl">收货人</view>
					<view class="fr between">
						<input type="text" class="intxt" v-model="username" placeholder="请输入收货人"
							placeholder-style="color:#CBCBCB">
						<!-- <view class="radios flex">
							<view class="s1 flex">
								<radio color="#4CD964" class="radio"></radio>先生
							</view>
							<view class="s1 flex">
								<radio color="#4CD964" class="radio"></radio>女士
							</view>
						</view> -->
					</view>
				</view>
				<view class="item flex">
					<view class="fl">联系方式</view>
					<view class="fr flex">
						<input type="text" v-model="mobile" class="intxt" placeholder="联系人手机号码"
							placeholder-style="color:#CBCBCB">
					</view>
				</view>

				<view class="item" @tap="editAddress" v-if="id>0">
					<button class="btn">编辑</button>
				</view>
				<view class="item" @tap="addAddress" v-else>
					<button class="btn">添加</button>
				</view>
			</view>
		</view>
	</view>
</template>

<script>
	import QQMapWX from '@/utils/qqmap-wx-jssdk.min.js' // 腾讯地图SDK （自己把腾讯地图SDK添加到自己指定的文件）
	export default {
		data() {
			return {
				show: false,
				longitude: '',
				latitude: '',
				markers: [{
					id: 1, //标记点id,Number类型，必填
					latitude: '', //纬度，必填
					longitude: '', //经度，必填
					title: '', //标注点名
					width: 24, //标注图标宽度，Number类型
					height: 32, //标注图标高度，Number类型
					iconPath: '', //显示的图标，必填
					// rotate:0,//旋转角度,顺时针旋转的角度，范围 0 ~ 360，默认为 0
					// alpha:1,//标注的透明度,默认1，无透明，范围 0 ~ 1
					label: {
						content: '',
						color: "#ffffff", //文本颜色
						fontSize: 12, //文字大小
						// borderWidth:30,//边框宽度
						// borderColor:'',//边框颜色
						// borderRadius:3,//边框圆角
						// bgColor:"#31c27c",//背景色
						padding: 3, //文本边缘留白
						textAlign: "center", //文本对齐方式。有效值: left, right, center
					}, //为标记点旁边增加标签
					// anchor:{},//经纬度在标注图标的锚点，默认底边中点,{x, y}，x表示横向(0-1)，y表示竖向(0-1)。{x: .5, y: 1} 表示底边中点
					//clusterId:1,//自定义点聚合簇效果时使用
					// customCallout:{},//自定义气泡窗口
					// aria-label:'',//无障碍访问，（属性）元素的额外描述
					joinCluster: false, //是否参与点聚合,此选项值必须设置为true,才会生效
					callout: { //自定义标记点上方的气泡窗口
						content: '', //文本
						color: "#ffffff", //文本颜色
						fontSize: 12, //文字大小
						borderRadius: 3, //callout边框圆角
						borderWidth: 30, //边框宽度
						borderColor: '', //边框颜色
						bgColor: "#31c27c", //背景色
						padding: 3, //文本边缘留白
						display: "ALWAYS", //'BYCLICK':点击显示; 'ALWAYS':常显
						textAlign: "center", //文本对齐方式。有效值: left, right, center
					},
				}],
				id: 0,
				username: '',
				mobile: '',
				province_id: 0,
				province_name: '',
				city_id: 0,
				city_name: '',
				area_id: 0,
				area_name: '',
				address: '',
				detailed_address: '',
				is_default: 0,
				actives: [0, 0, 0]
			}
		},

		onLoad(e) {
			this.id = e.id
			this.$nextTick(res => {
				this.getLocation()
			})
			//2023年6月18日08:06:43
			if (this.id) {
				this.addressDetail()
			}

		},
		onShow() {
			let _this = this
			// 重新获取定位
			uni.$on('againLocation', function() {
				_this.form = {
					name: '',
					area: '',
					location: '',
				}
				_this.getLocation()
			})
			// 解析传过来的位置
			uni.$on('getLocation', function(city, area) {
				let address = city + area
				_this.getMapAddress(address)
			})
		},
		methods: {
			// 选择地区回调
			selectArea(e) {
				console.log(e);
				this.province_id = e.province.value;
				this.province_name = e.province.label;

				this.city_id = e.city.value;
				this.city_name = e.city.label;

				this.area_id = e.area.value;
				this.area_name = e.area.label;

				this.address = this.province_name + this.city_name + this.area_name
				console.log(this.address)
			},
			async addressDetail() {
				const ret = await api.addressDetail({
					id: this.id
				});

				// uni.showToast({
				// 	title: ret.msg
				// })
				if (ret.status) {
					console.log(ret.data)
					// 跳转回上一页
					this.username = ret.data.username
					this.mobile = ret.data.mobile
					this.province_id = ret.data.province_id
					this.province_name = ret.data.province_name
					this.city_id = ret.data.city_id
					this.city_name = ret.data.city_name
					this.area_id = ret.data.area_id
					this.area_name = ret.data.area_name
					this.detailed_address = ret.data.detailed_address
					this.is_default = ret.data.is_default
					this.address = this.province_name + this.city_name + this.area_name;
					// cityData.forEach(function(el, index) {
					// 	if (el.id == this.province_id) {
					// 		this.actives[0] = index;
					// 		el.sub.forEach(function(sub1, index1) {
					// 			if (sub1.id == this.city_id) {
					// 				this.actives[1] = index1;
					// 				sub1.sub.forEach(function(sub2, index2) {
					// 					if (sub2.id == this.area_id) {
					// 						this.actives[2] = index2;
					// 					}
					// 				})
					// 			}
					// 		})
					// 	}
					// })
				} else {

				}

			},
			async addAddress() {
				const res = await api.addAddress({
					username: this.username,
					mobile: this.mobile,
					province_id: this.province_id,
					province_name: this.province_name,
					city_id: this.city_id,
					city_name: this.city_name,
					area_id: this.area_id,
					area_name: this.area_name,
					address: this.address,
					detailed_address: this.detailed_address,
					is_default: this.is_default
				});

				uni.showToast({
					title: res.msg
				})
				if (res.status) {
					// 跳转回上一页
					uni.$emit('ADD_ADDRESS', {
						addressData: 'ADD'
					});
					uni.navigateBack({

						delta: 1

					});
				} else {

				}

			},
			async editAddress() {
				const res = await api.editAddress({
					id: this.id,
					username: this.username,
					mobile: this.mobile,
					province_id: this.province_id,
					province_name: this.province_name,
					city_id: this.city_id,
					city_name: this.city_name,
					area_id: this.area_id,
					area_name: this.area_name,
					address: this.address,
					detailed_address: this.detailed_address,
					is_default: this.is_default
				});

				uni.showToast({
					title: res.msg
				})
				if (res.status) {
					// 跳转回上一页
					uni.$emit('ADD_ADDRESS', {
						addressData: 'ADD'
					});
					uni.navigateBack({

						delta: 1

					});
				} else {

				}

			},
			//定位
			init() {
				console.log(111)
				uni.getLocation({
					type: 'wgs84',
					success: (res) => {
						if (res.errMsg == "getLocation:ok") {
							console.log(res)
							this.setMap(res)
						}
					}
				});
			},

			//自带选址
			chooseLocation() {
				console.log(222)
				uni.chooseLocation({
					success: (res) => {
						console.log(res)
						this.form.name = res.name
						this.form.area = res.address
						this.form.location = this.util.formatLocation(res.longitude, res.latitude)
						this.setMap(res)
					}
				})
			},

			//设置地图坐标
			setMap(res) {
				console.log(res)
				this.longitude = res.longitude
				this.latitude = res.latitude
				// this.markers[0].longitude = res.longitude
				// this.markers[0].latitude = res.latitude
			},
			// 重新获取定位
			getLocation() {
				let _this = this
				uni.getLocation({
					type: 'wgs84', //wgs84
					success: function(res) {
						console.log(res)
						_this.getAddress(res.longitude, res.latitude).then(res => {
							_this.form = {
								name: res.result.ad_info.city,
								area: res.result.ad_info.district,
								// location: this.util.formatLocation(res.result.ad_info.location.lng,
								// 	res.result.ad_info.location.lat)
							}

							this.setMap(res)

						}).catch(res => {
							console.log(res)
						})
					},
					fail() {
						// 首次拒绝授权位置（根据自己要求配置或不配默认地址）
						_this.address = {
							city: '北京市',
							area: '',
							lng: '116.407526',
							lat: '39.904030'
						}
					}
				});
			},
			// 高德位置解析
			getMapAddress(address) {
				let _this = this
				return new Promise(function(resolve, reject) {
					uni.request({
						url: `https://restapi.amap.com/v3/geocode/geo?address=${ address }&key=1e8aba34389a21d169d1d0495106ef09`,
						method: "GET",
						success(res) {
							console.info("高德地图", res)
							if (res.data.status == 1) {
								const coordinate = res.data.geocodes[0].location.split(",")
								_this.address = {
									city: res.data.geocodes[0].city,
									area: res.data.geocodes[0].district.length != 0 ? res.data
										.geocodes[0].district : "",
									lng: coordinate[0],
									lat: coordinate[1],
								}
							}
							resolve();
						},
					});
				});
			},
			// 腾讯地图经纬度转中文地址
			getAddress(lng, lat) {
				return new Promise((resove, reject) => {
					const qqmapsdk = new QQMapWX({
						key: 'W4DBZ-C4LLD-4BK4C-P74JB-5YTCO-YLB3C', //之前在腾讯位置服务申请的key
					})
					qqmapsdk.reverseGeocoder({
						location: {
							latitude: lat,
							longitude: lng,
						},
						success: (res) => {
							console.log(res)
							resove(res)
						},
						fail: (e) => {
							reject(e)
						},
					})
				})
			}

		}

	}
</script>

<style>
	page {
		background: #F4F5F6;
	}

	::-webkit-scrollbar {
		width: 0;
		height: 0;
		color: transparent;
	}

	page {
		height: 100%;
		width: 100%;
		font-size: 24rpx;
	}

	image,
	view,
	input,
	textarea,
	label,
	text,
	navigator {
		box-sizing: border-box;
		color: #222;
		font-size: 28rpx;
	}

	image {
		width: 100%;
		height: 100%;
	}

	.line1 {
		white-space: nowrap;
		overflow: hidden;
		text-overflow: ellipsis;
	}

	.line2 {
		word-break: break-all;
		text-overflow: ellipsis;
		display: -webkit-box;
		-webkit-box-orient: vertical;
		-webkit-line-clamp: 2;
		overflow: hidden;
	}

	.flex {
		display: flex;
		align-items: center;
	}

	.center {
		display: flex;
		align-items: center;
		justify-content: center;
	}

	.between {
		display: flex;
		align-items: center;
		justify-content: space-between;
	}

	.btn {
		background: #f60;
		box-shadow: none;
		width: 100%;
		text-align: center;
		line-height: 92rpx;
		height: 92rpx;
		border-radius: 16rpx;
		color: #fff;
		border: 0;
		font-size: 32rpx;
	}

	.btn:active {
		opacity: 0.8;
	}

	.btn::after {
		display: none;
	}
</style>
<style lang="scss" scoped>
	.addaddress {
		height: 100%;
		overflow: hidden;

		.maps {
			height: 300rpx;
		}

		.box {
			padding: 0 30rpx;
			position: relative;
			margin-top: 20rpx
		}

		.form {
			background: #fff;
			border-radius: 24rpx;

			&.f2 {
				margin-top: 20rpx;
			}

			&.bd0 {
				border-bottom: 0;
			}

			.item {
				min-height: 108rpx;
				padding: 0 24rpx;

				.fl {
					width: 140rpx;
				}

				.fr {
					flex: 1;
					border-bottom: 1px solid #F4F5F6;
					padding: 40rpx 0;

					.yhname {}

					.area {
						padding-top: 20rpx;
						color: #a5a5a5;
					}

					.loca {
						width: 32rpx;
						height: 32rpx;
						margin-right: 8rpx;
					}

					.intxt {
						flex: 1;
						border: 0;
						background: none;
					}

					.radios {
						.s1 {
							margin-left: 15rpx;
						}

						.radio {
							transform: scale(0.65);
						}
					}
				}
			}

			.btn {
				border-radius: 48rpx;
				margin-top: 90rpx;
			}
		}
	}
</style>